import React from "react";
import { Button, Input, Form, Notify } from "react-vant";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { loginSuccess } from "../../app/user/userSlice";

export default () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const dispatch = useDispatch()
  const onFinish = async (values: any) => {
    const resp = await axios.post("/api/login", values);
    const { code, data } = resp.data;
    if (code === 200) {
      localStorage.setItem("token", data.token);
      console.log(data);
      dispatch(loginSuccess(data))
      Notify.show({ type: "success", message: "登录成功" });
      navigate(-1);
    } else {
      Notify.show({ type: "danger", message: "登录失败" });
    }
  };
	
  return (
    <Form
      form={form}
      onFinish={onFinish}
      footer={
        <div style={{ margin: "16px 16px 0" }}>
          <Button round nativeType="submit" type="primary" block>
            提交
          </Button>
        </div>
      }
    >
      <Form.Item
        rules={[{ required: true, message: "请填写用户名" }]}
        name="username"
        label="用户名"
      >
        <Input placeholder="请输入用户名" />
      </Form.Item>
      <Form.Item
        rules={[{ required: true, message: "请填写密码" }]}
        name="password"
        label="密码"
      >
        <Input placeholder="请输入密码" />
      </Form.Item>
    </Form>
  );
};
